package com.sysware.dom4j.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

public class JDomDemo {

	private static File xmlFile = new File("D://jdom.xml");

	public static void main(String[] args) throws Exception {
		 createFile();
		// updateValue("1,1", "3232");

		long start = System.currentTimeMillis();
		System.out.println(getValue("1,1", "name"));
		System.out.println(System.currentTimeMillis() - start);
	}

	public static String getValue(String id, String key) {
		try {
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(xmlFile);
			XPath xpath = XPath.newInstance("/children/data[id='" + id + "']");
			Object obj = xpath.selectSingleNode(document);
			if (obj == null)
				return null;
			Element ele = (Element) obj;
			return ele.getChildText(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void updateValue(File xmlFile, String id, String key, String value) {
		try {
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(xmlFile);
			XPath xpath = XPath.newInstance("/children/data[id='" + id + "']");
			Object obj = xpath.selectSingleNode(document);
			if (obj == null)
				return;
			Element ele = (Element) obj;
			Element child = ele.getChild(key);
			if(child == null) {
				child = new Element(key);
				ele.addContent(child);
			}
			
			child.setText(value);

			File file = new File("D://jdom_output.xml");
			tofile(document, file);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void createFile() {
		Element rootElement = new Element("children");
		Document document = new Document(rootElement);
		for (int i = 0; i < 5000; i++) {
			for (int j = 0; j < 30; j++) {
				Element data = new Element("data");
				Element id = new Element("id");
				id.setText("" + i + "," + j);
				data.addContent(id);

				Element name = new Element("name");
				name.setText("name-[" + i + "][" + j + "]");
				data.addContent(name);
				rootElement.addContent(data);
			}
		}

		tofile(document, xmlFile);
	}

	public static void tofile(Document document, File file) {
		// 用来输出XML文件
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
		// 设置输出编码
		out.setFormat(out.getFormat().setEncoding("UTF-8"));
		try {
			// 输出XML文件
			out.output(document, new FileOutputStream(file));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
